package br.com.kmproaudio.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.kmproaudio.core.JavaMailApp;
import br.com.kmproaudio.model.Contato;

/**
 * O Servlet implementation class Index
 */
@WebServlet(urlPatterns = {"/contato", "/Contatos"})

public class Contatos extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Contatos() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		String action = request.getParameter("action");
		String tipo = request.getParameter("tipo");
		String retorno = "view/site/contato.jsp";
		
		if(action != null){
			if(action.equals("EnviarEmail")){
				Contato contato = new Contato();
				contato.setNome(request.getParameter("nome"));
				contato.setEmail(request.getParameter("email"));
				contato.setTelefone(request.getParameter("telefone"));
				contato.setMensagem(request.getParameter("mensagem"));
				
				try {
					JavaMailApp email = new JavaMailApp();
					
					if(tipo.equals("contato")){
						email.enviaEmail(contato, 0); //Ao cliente
						email.enviaEmail(contato, 1); //À KM
						request.setAttribute("msg", "Mensagem encaminhada com sucesso!");
					}else{
						email.enviaEmail(contato, 2);
						retorno = "view/site/index.jsp";
						request.setAttribute("msg", "Assinatura realizada com sucesso!");
					}
										
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					request.setAttribute("msg", "Ocorreu algum erro no sistema.  Favor tentar novamente!");  
				}
			}		
		}
		RequestDispatcher rd = request.getRequestDispatcher(retorno);
		rd.forward(request, response);
	}

}
